package com.sx.wechat.controller.teacher;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sx.core.utils.PropertyUtils;
import com.sx.wechat.controller.BaseController;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.UUID;

/**
 * Created by lihao1 on 7/15/15.
 */
@RestController
@RequestMapping(value = "ue")
public class UeditorController extends BaseController {
    String[] picFileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
    private String fileLocation= PropertyUtils.getProperty("file.location");
    private String fileUrl= PropertyUtils.getProperty("file.url");
    @RequestMapping(value = "upload")
    public String ueditor(HttpServletRequest request, HttpServletResponse response){
        try{
            request.setCharacterEncoding("utf-8");
            response.setHeader("Content-Type" , "text/html");
            response.setHeader("X-Frame-Options", "SAMEORIGIN");
            String action = request.getParameter("action");
            if(StringUtils.equals("uploadimage",action)){

                MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
                Iterator list             = multipartRequest.getFileNames();
                while (list.hasNext()) {
                    String               controlName = list.next().toString();
                    MultipartFile file        = multipartRequest.getFile(controlName);



                    String fileName = file.getOriginalFilename();
                    File fileOnServer = null;

                    String static_dir="attach";
                    String dir_str = FilenameUtils.normalize(fileLocation + File.separator+static_dir+File.separator);
                    File dir=new File(dir_str);
                    if(!dir.exists()){
                        dir.mkdirs();
                    }

                    String ext=FilenameUtils.getExtension(fileName);
                    fileName= UUID.randomUUID().toString()+"."+ext;
                    fileOnServer=new File(dir,fileName);
                    try {
                        byte[] bytes = file.getBytes();
                        FileUtils.writeByteArrayToFile(fileOnServer,bytes);
                    } catch (IOException e) {
                        logger.error(e);
                    }
//                    String httpPath=fileUrl.endsWith("/")?(fileUrl+static_dir+"/"+fileName):fileUrl+"/"+static_dir+"/"+fileName;
                    String httpPath=static_dir+"/"+fileName;
//
//
////                    CommonsMultipartFile cmf         = (CommonsMultipartFile) file;
////                    DiskFileItem fileItem    = (DiskFileItem) cmf.getFileItem();
////                    if(fileItem!=null && fileItem.getSize()>12*1024*1024){
////                        return "<script>alert('文件不能大于12M')</script>";
////                    }
//                    String fileName=null,str=null,ext=null;
//                    fileName    = file.getName();
//                    if(StringUtils.isEmpty(fileName)){
//                        continue;
//                    }
//                    str         = randomName(fileName);
//                    ext=getExtension(fileName);
//                    if(Arrays.binarySearch(picFileType, ext)==-1){
//                        continue;
//                    }
//                    File fileOnServer      = new File(dir,str);
//
//                    byte[] bytes = file.getBytes();
//                    FileUtils.writeByteArrayToFile(fileOnServer,bytes);

//                    String httpPath= (fileUrl.endsWith("/")?fileUrl:fileUrl+"/")+"ue"+"/"+pk+"/"+str;
                    String callback = request.getParameter("callback");
                    String result = "{\"name\":\""+ fileOnServer.getName() +"\", \"original\": \""+ file.getName() +"\", \"size\": "+ file.getSize() +", \"state\": \"SUCCESS\", \"type\": \""+ ext +"\", \"url\": \""+ httpPath +"\"}";
                    result = result.replaceAll( "\\\\", "/" );
                    if( callback == null ){
                        return result;
//                        writer.print( result);
                    }else{
                        return "<script>" + callback + "(" + result + ")</script>";
                    }
                }
            }else if(StringUtils.equals("config",action)){
                JSONObject node = new JSONObject();
                node.put("imageActionName","uploadimage");
                node.put("upfile","upfile");
                node.put("imageMaxSize",2048000);
                JSONArray arrayNode= new JSONArray();
                arrayNode.add(".png");
                arrayNode.add(".jpg");
                arrayNode.add(".jpeg");
                arrayNode.add(".gif");
                arrayNode.add(".bmp");
                node.put("imageAllowFiles",arrayNode);
                node.put("imageCompressEnable",true);
                node.put("imageCompressBorder",1600);
                node.put("imageInsertAlign","none");
                node.put("imageUrlPrefix",fileUrl);
//                node.put("imagePathFormat","/updload/ue/{yyyy}{mm}{dd}{time}{rand:6}");
                String configContent=node.toJSONString();
                return configContent;
            }

        }catch (Exception e){

            logger.error("upload sensor fail", e);
            String msg = "上传失败";
//            writer.print("{\"success\":false,\"msg\":\"" + msg + "!\"}");
            return "{\"success\":false,\"msg\":\"" + msg + "!\"}";
        }finally {

        }
        return null;
    }
    private String filter(String input) {
        return input.replaceAll("/\\*[\\s\\S]*?\\*/", "");
    }
}
